package com.lmc.chatroom.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lmc.chatroom.component.onlineUserManager;
import com.lmc.chatroom.mapper.friendMapper;
import com.lmc.chatroom.mapper.messageMapper;
import com.lmc.chatroom.mapper.sessionMapper;
import com.lmc.chatroom.model.*;
import com.lmc.chatroom.service.messageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;


@Slf4j
@Component
public class addMessagAPI extends TextWebSocketHandler {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private sessionMapper sessionMapper;
    @Autowired
    private onlineUserManager onlineUserManager;
    @Autowired
    private friendMapper friendMapper;
    @Autowired
    private messageMapper messageMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("websocket已连接");
        User user = (User)session.getAttributes().get("user");
        if(user==null){
            return;
        }
        onlineUserManager.online(user.getUserId(),session);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到新增的消息"+message.getPayload());
        //获取用户信息
        User user  = (User) session.getAttributes().get("user");
//        获取消息内容并使用message对象接收
        String payload = message.getPayload();
        //请求载荷是一个JSON格式，需要将其转换成JAVA对象
        MessageRequest messageRequest = objectMapper.readValue(payload, MessageRequest.class);
        if (messageRequest.getType() .equals("message") ){
            transferMessage(user,messageRequest);

        }else {
            log.info("[websocket] req.type有误"+messageRequest.getType());
            return;
        }

    }

    private void transferMessage(User fromUser, MessageRequest messageRequest) throws IOException {
//        1.先构造一个messageResponse对象
        MessageResponse rsp = new MessageResponse();
        rsp.setFromName(fromUser.getUsername());
        rsp.setFromId(fromUser.getUserId());
        rsp.setType("message");
        rsp.setContent(messageRequest.getContent());
        rsp.setSessionId(fromUser.getUserId());
        rsp.setSessionId(fromUser.getUserId());
//        把这个对象变成json格式
        String respJson = objectMapper.writeValueAsString(rsp);
        log.info("[transferMessage] respJson:"+respJson);
//        2.根据sessionId，在数据库中查出该对话中的所有用户
        Integer friendId = sessionMapper.selectFriendIdBySessionId(messageRequest.getSessionId(), fromUser.getUserId());
        Friend friend = friendMapper.getFriend(friendId);
//        3.将消息给上述的每个用户都发一份
        WebSocketSession webSocketSession1 = onlineUserManager.getSession(friend.getFriendId());
        if(webSocketSession1!=null){
            webSocketSession1.sendMessage(new TextMessage(respJson));
        }
        WebSocketSession webSocketSession2 = onlineUserManager.getSession(fromUser.getUserId());
        webSocketSession2.sendMessage(new TextMessage(respJson));

//        4.将转发的消息放到数据库中
        message message = new message();
        message.setContent(messageRequest.getContent());
        message.setFromId(fromUser.getUserId());
        message.setSessionId(messageRequest.getSessionId());
        messageMapper.insertMessge(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("Websocket连接异常");
        User user = (User)session.getAttributes().get("user");
        if(user==null){
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("Websocket断开连接");
        User user = (User)session.getAttributes().get("user");
        if(user==null){
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }
}
